<?php
if(!defined("YUEXUAN_REAL_ROOT_PATH")){
	exit("Access Denied.");
}

class accountException extends Exception {
	// pass
}

/**
 * 账户管理
 * @author tongjun
 *
 */
class tally_account extends base {
	private $accountTableName = "#tablePre#account";
	
	// 读取所有账号列表
    public function findAccountList($userId, $showHide=false, $accountType=null){
    	$where = "";
    	if(!$showHide){
    		$where .= " and isShow=1 ";
    	}
    	if($accountType!=null){
    		$where .= " and accountType={$accountType} ";
    	}
    	$sql = "select * from {$this->accountTableName} " .
    			"where userId={$userId} {$where} " .
    			"order by orderIndex asc, id asc ";
    	return $this->db(ext_dbHandle::$slaveDbServer)->getRows($sql);
    }
	
    // 根据账号id读取账户信息
    public function findAccountByAccountId($userId, $accountId){
    	$sql = "select * from {$this->accountTableName} " .
    			"where userId={$userId} and id={$accountId}";
    	return $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    }
    
	// 创建新的账户
	public function createAccount($userId, $type, $accountName,
			$desc='', $orderIndex=999, $show=1){
		$sql = "select * from {$this->accountTableName} " .
    			"where userId={$userId} and name='{$accountName}'";
    	$oldRow = $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    	if($oldRow){
    		throw new accountException("此账户[".$accountName."]己存在");
    	}
		$defaultAccountInfo = array(
			"createTime" => date("Y-m-d H:i:s")
		);
		$accountInfo = array(
			"userId" => $userId,
			"accountType" => $type,
			"name" => $accountName,
			"description" => $desc,
			"currentValue" => 0,
			"orderIndex" => $orderIndex,
			"isShow" => $show
		);
		$accountInfo = array_merge($defaultAccountInfo, $accountInfo);
		$this->db(ext_dbHandle::$masterDbServer)->insert($this->accountTableName, $accountInfo);
		return $this->db(ext_dbHandle::$masterDbServer)->insert_id();
	}

	public function findAccountByName($userId, $accountName){
		$sql = "select * from {$this->accountTableName} " .
			"where userId={$userId} and name='{$accountName}'";
		return $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
	}

	public function findOrCreateAccountId($userId, $accountName, $orderIndex=999, $isShow=0){
		$oldRow = $this->findAccountByName($userId, $accountName);
		if($oldRow){
			return $oldRow["id"];
		}else{
			return $this->createAccount($userId, 0, $accountName,
			'', $orderIndex, $isShow?1:0);
		}
	}
    
	// 更新账户信息
	public function updateAccountInfo($userId, $accountId, $accountInfo){
		$sql = "select * from {$this->accountTableName} " .
    			"where userId={$userId} and name='{$accountInfo["name"]}' and id<>{$accountId}";
    	$oldRow = $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    	if($oldRow){
    		throw new accountException("此账户[".$accountInfo["name"]."]己存在");
    	}
		$where = array(
			"id" => $accountId, 
			"userId" => $userId,
		);
		$this->db(ext_dbHandle::$masterDbServer)->update($this->accountTableName, $accountInfo, $where);
	}
	
	// 更新账户余额
	public function updateAccountCurrentValue($userId, $accountId, $moneyIn, $moneyOut){
//		echo $accountId.'<br>';
		$accountInfo = $this->findAccountByAccountId($userId, $accountId);
		if(!$accountInfo){
			throw new accountException("此账户[".$accountId."]不存在");
		}
		$accountInfo["currentValue"]+=($moneyIn-$moneyOut);
		$this->updateAccountInfo($userId, $accountId, $accountInfo);
	}
	
	// 设置默认账户
	public function setDefaultAccount($userId, $accountId){
		$db = $this->db(ext_dbHandle::$masterDbServer);
		$sql = "update {$this->accountTableName} set isDefault=0 " . "where userId={$userId} and id<>{$accountId}";
		$db->begin();
		try {
			$db->exc ( $sql );
			$accountInfo = array (
					"isDefault" => 1,
					"isShow" => 1 
			);
			$where = array (
					"id" => $accountId,
					"userId" => $userId 
			);
			$db->update ( $this->accountTableName, $accountInfo, $where );
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollback ();
			throw $e;
		}
	}
	
	// 删除账户
	public function removeAccount($userId, $accountId){
		$db = $this->db(ext_dbHandle::$masterDbServer);
		$flowClass = new tally_flow ();
		$db->begin ();
		try {
			$flowClass->removeFlowByAccountId ( $userId, $accountId );
			
			$sql = "delete from {$this->accountTableName} " . "where userId={$userId} and id={$accountId}";
			$db->exc ( $sql );
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollback ();
			throw $e;
		}
	}
	
	// 删除用户的所有账户
	public function removeAccountByUserId($userId){
		$accountList = $this->findAccountList($userId, true);
		if($accountList){
			foreach($accountList as $account){
				$this->removeAccount($userId, $account["id"]);
			}
		}
	}
	
	// 统计资产
	public function getAsset($userId){
		$sql = "select sum(currentValue) as s from {$this->accountTableName} " .
				"where userId={$userId} and currentValue>0 and isShow=1";
		$row = $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    	return $row["s"];
	}
	
	// 统计负债
	public function getOwed($userId){
		$sql = "select sum(currentValue) as s from {$this->accountTableName} " .
				"where userId={$userId} and currentValue<0 and isShow=1";
		$row = $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    	return $row["s"];
	}
}
